package com.ele.client.activity.editor.widget;

import com.ele.model.Answer;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.TextArea;
import com.github.gwtbootstrap.client.ui.event.CloseEvent;
import com.github.gwtbootstrap.client.ui.event.CloseHandler;
import com.github.gwtbootstrap.client.ui.event.ClosedEvent;
import com.github.gwtbootstrap.client.ui.event.ClosedHandler;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Widget;

public class AnswerEditorWidget extends Composite implements IsEditorWidget<Answer> {

    interface DefaultUiBinder extends UiBinder<Widget, AnswerEditorWidget> {}
    private static DefaultUiBinder uiBinder = GWT.create(DefaultUiBinder.class);

    @UiField
    TextArea textArea;
    @UiField
    Button deleteButton;

    private Long answerId;

    public AnswerEditorWidget(Answer answer) {
        HorizontalPanel widget = (HorizontalPanel) uiBinder.createAndBindUi(this);
        initWidget(widget);
        DOM.setElementProperty(widget.getElement(), "cellPadding", "1");

        setValue(answer);
    }

    @Override
    public HandlerRegistration addCloseHandler(CloseHandler handler) {
        return addHandler(handler, CloseEvent.getType());
    }

    @Override
    public HandlerRegistration addClosedHandler(ClosedHandler handler) {
        return addHandler(handler, ClosedEvent.getType());
    }

    @Override
    public void setValue(Answer value) {
        if (value != null) {
            answerId = value.getId();
            textArea.setValue(value.getText());
        }
    }

    @Override
    public void setFocus(boolean focused) {
        textArea.setFocus(focused);
    }

    @Override
    public Answer getValue() {
        Answer answer = new Answer();
        answer.setId(answerId);
        answer.setText(textArea.getText());

        return answer;
    }

    @UiHandler("deleteButton")
    void onDeleteClick(ClickEvent event) {
        fireEvent(new ClosedEvent());
    }

    @UiHandler("textArea")
    public void onTextAreaFocus(FocusEvent event) {
        int pos = textArea.getValue().indexOf("...");
        if (pos >= 0) {
            textArea.setSelectionRange(pos, 3);
        }
    }
}
